<template>
    <el-dialog v-model="baTable.table.extend!.showDeliveryDialog" class="ba-operate-dialog" height="70%">
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ $t('shop.order.order.Order shipment') }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar" noresize>
            <el-tabs v-model="activeName" class="delivery-tabs" @tabChange="onChangeDeliveryList" stretch>
                <el-tab-pane label="未发货信息" name="unShipped" border>
                    <Table ref="unShippedRef" :key="tableKey" :pagination="false" style="height: 165px">
                        <template #goodsNum>
                            <el-table-column :label="$t('shop.order.order.delivery_num')" align="center" width="140" fixed="right">
                                <template #default="{ row }">
                                    <el-input-number
                                        v-model="row.deliveryNum"
                                        :min="1"
                                        :max="row.num - row.delivery_num > 0 ? row.num - row.delivery_num : 1"
                                        size="small"
                                    />
                                </template>
                            </el-table-column>
                        </template>
                    </Table>
                </el-tab-pane>
                <el-tab-pane label="已发货信息" name="shi   pped">
                    <Table ref="shippedRef" :key="tableKey" :pagination="false" style="height: 165px">
                        <template #goodsNum>
                            <el-table-column :label="$t('shop.order.order.delivery_num')" align="center">
                                <template #default="{ row }">
                                    <el-text>{{ row.delivery_num }}/{{ row.num }}</el-text>
                                </template>
                            </el-table-column>
                        </template>
                    </Table>
                </el-tab-pane>
            </el-tabs>
            <el-form ref="formRef" :model="deliveryForm" :rules="deliveryFormRules">
                <el-form-item :label="$t('shop.order.order.Shipment Type')" prop="type">
                    <el-radio-group v-model="deliveryForm.type">
                        <el-radio value="1" border>{{ $t('shop.order.order.Express delivery') }}</el-radio>
                        <el-radio value="2" border>{{ $t('shop.order.order.No need to ship') }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <view v-if="isNeedToDelivery">
                    <FormItem
                        :label="$t('shop.order.order.delivery_company')"
                        prop="delivery_company_id"
                        v-model="deliveryForm.delivery_company_id"
                        :placeholder="t('Please input field', { field: t('shop.order.order.delivery_company') })"
                        type="remoteSelect"
                        :input-attr="{
                            remoteUrl: '/admin/shop.delivery.company/index',
                            pk: 'id',
                            field: 'name',
                        }"
                    />
                    <FormItem
                        :label="$t('shop.order.order.delivery_no')"
                        prop="delivery_no"
                        v-model="deliveryForm.delivery_no"
                        :placeholder="t('Please input field', { field: t('shop.order.order.delivery_no') })"
                        type="string"
                    />
                </view>
            </el-form>
        </el-scrollbar>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="baTable.table.extend!.showDeliveryDialog = false">{{ $t('Cancel') }}</el-button>
                <el-button type="primary" @click="confirmDelivery(formRef)">{{ $t('Confirm') }}</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { inject, ref, reactive, computed, provide, onMounted, nextTick } from 'vue'
import baTableClass from '/@/utils/baTable'
import { getDeliveryCompany, delivery } from '/@/api/backend/shop/order/order'
import { ElNotification, TabPaneName, type FormInstance, type FormRules } from 'element-plus'
import { buildValidatorData } from '/@/utils/validate'
import { useI18n } from 'vue-i18n'
import { baTableApi } from '/@/api/common'
import { uuid } from '/@/utils/random'
import Table from '/@/components/table/index.vue'
import FormItem from '/@/components/formItem/index.vue'

const { t } = useI18n()

const baTable = inject('baTable') as baTableClass

const formRef = ref<FormInstance>()

type DeliveryCompany = {
    id: string
    name: string
    code: string
}
const deliveryCompany = ref<DeliveryCompany[]>([])

interface DeliveryForm {
    order_id: string
    type: string
    delivery_company_id: number
    delivery_company: string
    delivery_code: string
    delivery_no: string
}
const deliveryForm = ref(<DeliveryForm>{
    type: '1',
    delivery_company_id: 0,
    delivery_company: '',
    delivery_code: '',
    delivery_no: '',
})

const deliveryFormRules = reactive<FormRules>({
    type: [buildValidatorData({ name: 'required', title: t('shop.order.order.Shipment Type') })],
    delivery_company_id: [buildValidatorData({ name: 'required', title: t('shop.order.order.delivery_company') })],
    delivery_no: [buildValidatorData({ name: 'required', title: t('shop.order.order.delivery_no') })],
})

const isNeedToDelivery = computed(() => {
    return deliveryForm.value.type == '1'
})

//发货
const confirmDelivery = (form: FormInstance | undefined) => {
    if (!form) return
    let deliveryData: {
        goods_id: number
        order_detail_id: number
        delivery_num: number
    }[] = []
    deliveryTable.table.selection?.map((item) => {
        deliveryData.push({
            order_detail_id: item.id,
            delivery_num: item.deliveryNum,
            goods_id: item.goods_id,
        })
    })
    if (deliveryData.length == 0) {
        return ElNotification.error({
            message: '请选择要发货的商品',
        })
    }
    form.validate((valid) => {
        if (!valid) return
        delivery({
            delivery_company_id: deliveryForm.value.delivery_company_id,
            type: deliveryForm.value.type,
            delivery_no: deliveryForm.value.delivery_no,
            order_id: baTable.table.extend!.orderData.id,
            delivery_data: deliveryData,
        }).then(() => {
            baTable.table.extend!.showDeliveryDialog = false
            baTable.table.extend!.showDetailDialog = false
            baTable.onTableHeaderAction('refresh', {})
        })
    })
}

const activeName = ref('unShipped')

// 未发货列表
const unShippedList = computed(() => {
    return baTable.table.extend!.orderData.detail.filter((item: any) => {
        return item.delivery_num < item.num
    })
})
// 已发货
const shippedList = computed(() => {
    return baTable.table.extend!.orderData.detail.filter((item: any) => {
        return item.delivery_num > 0
    })
})
const tableKey = ref(uuid())

const deliveryTable = new baTableClass(new baTableApi(''), {
    pk: 'id',
    column: [
        {
            type: 'selection',
            align: 'center',
            operator: false,
            selectable: () => {
                return activeName.value === 'unShipped'
            },
        },
        {
            label: t('shop.order.order.goods_name'),
            prop: 'goods_name',
            align: 'center',
            operatorPlaceholder: t('Fuzzy query'),
            operator: false,
            sortable: false,
        },
        {
            label: t('shop.order.order.goods_spec'),
            prop: 'spec',
            align: 'center',
            operatorPlaceholder: t('Fuzzy query'),
            operator: false,
            sortable: false,
        },
        { label: t('shop.order.order.goods_logo'), prop: 'image', align: 'center', render: 'image', operator: false },
        {
            label: t('shop.order.order.pay_price'),
            prop: 'pay_price',
            align: 'center',
            operatorPlaceholder: t('Fuzzy query'),
            operator: false,
            sortable: false,
        },
        {
            render: 'slot',
            slotName: 'goodsNum',
        },
    ],
    dblClickNotEditColumn: ['all'],
})

const unShippedRef = ref()

provide('baTable', deliveryTable)

//物流列表切换
const onChangeDeliveryList = (name: TabPaneName) => {
    if (name == 'unShipped') {
        deliveryTable.table.data = unShippedList.value
    } else {
        deliveryTable.table.data = shippedList.value
    }
}

// 全选未发货列表
const selectAllUnshipped = () => {
    unShippedRef.value.getRef().toggleAllSelection()
}

onMounted(() => {
    baTable.table.extend!.orderData.detail.forEach((item: any) => {
        item.deliveryNum = item.num - item.delivery_num
    })
    deliveryTable.table.data = unShippedList.value
    getDeliveryCompany().then((res) => {
        if (res.code) {
            deliveryCompany.value = res.data.list
        }
    })
    nextTick(() => {
        selectAllUnshipped()
    })
})
</script>

<style scoped lang="scss">
.title {
    font-size: 20px;
}

.delivery-tabs {
    margin-bottom: 50px;
}
</style>
